package com.atguigu.flink0922.chapter07.state;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Iterator;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/6 11:43
 */
public class Flink01_State_Operator_List {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.enableCheckpointing(1000);
    
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MyMapFunction())
            .print();
    
    
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static class MyMapFunction implements MapFunction<String, String>, CheckpointedFunction {
        long count = 0;
        private ListState<Long> state;
    
        @Override
        public String map(String value) throws Exception {
            count ++;
            state.clear();
            state.add(count);
            return count + "";
        }
    
        // 初始化算子状态
        @Override
        public void initializeState(FunctionInitializationContext context) throws Exception {
            System.out.println("initializeState...");
//            state = context.getOperatorStateStore().getListState(new ListStateDescriptor<Long>("state", Long.class));
            state = context.getOperatorStateStore().getUnionListState(new ListStateDescriptor<Long>("state", Long.class));
    
            final Iterator<Long> it = state.get().iterator();
            if (it.hasNext()) {
                count = it.next();
            }
        }
        // 做checkpoint的时候会调用这个方法, 在这里可以写持久化.
        @Override
        public void snapshotState(FunctionSnapshotContext context) throws Exception {
            System.out.println("snapshotState...");
            state.clear();
            state.add(count);
        }
    }
}
